require 'System::Net'
require 'System::Text'
require 'System::Collections'
require 'System::Collections::Specialized'
require 'System::Windows::Media::Imaging'

URLS = {
        :auth => "http://twitter.com/account/verify_credentials.json",
        :friends => "http://twitter.com/statuses/friends_timeline.json",
        :update => "http://twitter.com/statuses/update.json",
        :search => "http://search.twitter.com/search.json"
}

class TwitterXamlPresenter
  def add_to_status_list(json)
    json.each do |status|
      if me.shell.find_name(status.id.to_s).nil?
        panel = StackPanel.new()
        panel.name = status.id.to_s
        img = Image.new()
        img.source = BitmapImage.new(System::Uri.new(status.user.profile_image_url.Replace("\\", ""), UriKind.Absolute))
        img.width = 50
        img.height = 50
        tb = TextBlock.new()
        tb.text = "#{status.user.name.Replace('\\', '')}: #{status.text.Replace('\\', '')}"
        panel.children.add(img)
        panel.children.add(tb)
        me.status_list.children.add(panel)
      end
    end
  end
end

class TwitterHtmlPresenter
  def add_to_status_list(json)
    json.each do |status|
      if (document.GetElementById(status.id.to_s).nil?)
        document.msg.innerHTML += %{<div id=\"#{status.id.to_s}\" style=\"clear:both;\">
					<img style=\"float:left\" src=\"#{status.user.profile_image_url.Replace('\\', '')}\" />
					#{status.user.name.Replace('\\', '')}: #{status.text.Replace('\\', '')}<br/>#{status.created_at}</div>}
      end
    end
  end
end

class Twitter
  attr_accessor :presenters
  def initialize
    @hash = ""
    @presenters = []
  end

  def credentials(username, password)
    utf8 = UTF8Encoding();
    @hash = Convert.ToBase64String(utf8.GetBytes("#{username}:#{password}"))
  end

  def friends_timeline
    fetch(URLS[:friends])
  end

  def update(msg)
    url = "#{URLS[:update]}?status=#{msg}"
    fetch(url, "POST")
  end

  def search(query_terms, query_string=nil)
    url = URLS[:search]
    if(query_string)
      url += query_string
    else
      url += "?q=" + query_terms
    end
    fetch(url)
  end

  def update_status_list(sender, args)
    if(args.Error.nil?)
      resp = JsonValue.Parse(args.Result)
      @presenters.each do |presenter|
        presenter.add_to_status_list(resp)
      end
    else
      log(args.Error)
    end
  end

  def fetch(uri, method="GET")
    client = WebClient.new()
    proxy = "http://localhost/gestalt/TwitterProxy.ashx?u=#{HttpUtility.UrlEncode(uri)}&m=#{HttpUtility.UrlEncode(method)}"
    if(self.hash)
      proxy += "&ph=#{HttpUtility.UrlEncode(@hash)}"
    end
    log("calling #{proxy}")
    client.DownloadStringAsync(System::Uri.new(proxy, UriKind.Absolute))
    client.DownloadStringCompleted do |s,e|update_status_list(s,e) end  #how do we do delegate assignment in IR?
  end
end

# methods for the control are not in a class, but made here for delegates. 

def log(msg)
  document.debug.innerHTML = msg.to_s
end

def login_event(sender, eventagrs)
  @@twitter ||= Twitter.new()
  @@twitter.credentials(me.username.text.trim, me.password.password.trim)
  @@twitter.friends_timeline()
end

def update_status_event(sender, eventargs)
  log("updating status")
  @@twitter.update(me.my_status.text)
  @@twitter.friends_timeline()
end

#wire up the form
me.update.click{|s, a| login_event(s, a) }
me.update_my_status.click{ |s, a| update_status_event(s, a) }
